<script lang="ts" setup>
import type { DataType } from './types';
// import { ref,onMounted,reactive  } from 'vue';
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import {  VbenButton } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { Page } from '@vben/common-ui';

import {
  Button,
  message,
  Modal,
  Popconfirm,
  Space,
  Tooltip,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteArticle,
  deleteMultiple,
  getArticle,
  getArticleSelectCategorys,
  postArticleStatus,
  getdownloadtemplate,
  exportdata,
  importdata
} from '#/api/portal/article';
import { getYears } from '#/api/admin/year';

import Icon from '#/components/Icons';
import { formatImagesList, queryStringToObject } from '#/utils';

defineOptions({
  name: 'PortalPartsArticleIndex',
});

const baseUrl = import.meta.env.VITE_GLOB_API_URL
const categoriesTree = ref([]);
const yearOptions = ref([]); // ✅ 外部定义，响应式
const gridRef = ref();

const route = useRoute();
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');
const code = ref('');



const modalVisible = ref(false); // 控制 Modal 显示
const selectedRows = ref<DataType[]>([]); // 存放选中的行
const onCheckboxChange = ({ records }) => {
  console.log(records)
  selectedRows.value = records;
};

const nameEditRender = reactive({
  name: 'input',
  events: {
    input (cellParams) {
      const { row, column } = cellParams
    }
}
});

const gridOptions: VxeGridProps<DataType> = {
  checkboxConfig:{
    range: true, // 可选：支持 shift 连选
   
  },
  rowConfig: {
    isCurrent: true,
    isHover: true,
  },
  editConfig: {
    trigger: 'click',
    mode: 'row'
  },
  columns: [
    { field: 'id', title: $t('page.common.Code'),type:'checkbox' },
    { field: 'post_title', title: $t('page.common.Accessory Name'), slots: { default: 'post_title' }},
    { field: 'category_names', title: $t('page.common.Category') },
    { field: 'thumbnail', title: $t('page.common.Thumbnail'), cellRender: { name: 'CellImage' } },
    { field: 'post_status', title: $t('page.common.Status'), slots: { default: 'status' } },
    {
      field: 'update_time',
      title: $t('page.common.UpdatedTime'),
      formatter: 'formatShortDateTime',
    },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: $t('page.common.Action'),
      width: 280,
    },
  ],
  height: 'auto',

  keepSource: true,
  pagerConfig: {
    layouts: ['Total', 'Sizes', 'PrevPage', 'Number', 'NextPage', 'FullJump'], // 带总条数和每页大小选择
    pageSize: 15,
  
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const param = queryStringToObject(route.meta.param as string);
        if (param?.code) {
          formValues.code = param.code;
          code.value = param.code;
        }

        const { data } = await getArticle({
          page: page.currentPage,
          limit: page.pageSize,
          ...formValues,
        });
        const total = data.list.length;
       
        data.list = formatImagesList(data.list, 'thumbnail');
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    //  export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },

   exportConfig: {
        enabled: true,
         modes: [
            { label: '当前页', value: 'current-page' },
            { label: '所有数据', value: 'All' },
            { label: '当前筛选数据', value: 'current' },
          ],
          types: ['xlsx'],
        exportMethod({ options}) {

          return exportdata(options)
          
            .then(response => {
              const url = response.data.url;

              const a = document.createElement('a');
              a.href = url;
              a.download = '导出文件.xlsx';
              document.body.appendChild(a);
              a.click();
              a.remove();

              return true;
            })
            .catch(() => {
              return false;
            });
        },
        filename: '导出数据',
       
        sheetName: 'Sheet1',
        remote: true,
        download: true,
        allData: true,
        columns: []
   },

  importConfig: {
        mode: 'covering',
        remote: true,
        types: ['xlsx'],
        async importMethod({ file }) {
          const formData = new FormData();
          formData.append('file', file);
          try {
            const res = await importdata(formData); // 你封装的上传方法

            if (res.code === 1) {
              message.success(res.msg || '上传成功');
               GridApi.query();
            } else {
              message.success(res.msg || '上传失败');
            }
          } catch (error) {
            message.success('服务器错误，上传失败');
          }
        }
  },

};
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['code'],
      },
      fieldName: 'code',
      label: 'code',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: $t('page.common.Please Enter')+` ${viewTitle}`,
      },
      fieldName: 'keyword',
      label: $t('page.common.Title'),
    },
    {
        component: 'Select',
        fieldName: 'post_status',
        label: $t('page.common.Status'),
        componentProps: {
          placeholder: $t('page.common.Please Select')+' '+$t('page.common.Status'),
          options: [  // ✅ 正确的属性名是 `options`，不是 `data`
            { label: 'Publish', value: 1 },
            { label: 'Trash', value: 0 },
          ],
        },
      },

    {
      component: 'TreeSelect',
      componentProps: {
        treeData: categoriesTree.value,
        multiple: true, // ✅ 启用多选
        fieldNames: {
          value: 'id',
          key: 'id',
          label: 'name',
          children: 'children',
        },
        placeholder: $t('page.common.Please Select') + ` ${viewTitle} `+$t('page.common.Category'), // 可选，增强体验
        allowClear: true, // 可选，添加清除按钮
      },
      fieldName: 'category_id',
      label: $t('page.common.Category'),
    }

  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  // 按下回车时是否提交表单
  submitOnEnter: true,
};
const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});

const handleDelete = async (row: DataType) => {
  const $table = GridApi.grid;
  if ($table) {
    const { msg } = await deleteArticle(row.id);
    $table.remove(row);
    message.success(msg);
  }
};




const handleChangeStatus = async (
  row: DataType,
  type: 'publish' | 'recommended' | 'top',
) => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要执行此操作吗?`,
    async onOk() {
      const { msg } = await postArticleStatus({ id: row.id, type });
      message.success(msg);
      GridApi.query();
    },
  });
};

const openDialog = async (row?: DataType) => {
  const id = row?.id || 0;
  // 这里就是路由跳转，也可以用path

  router.push({
    name: `PortalParts${code.value}Detail`,
    params: { code: code.value, id },

  });
};

const openDeleteConfirm = () => {

  const $table = GridApi.grid;
    const selectedRows = $table.getCheckboxRecords();
    console.log(selectedRows)
  if (selectedRows.length === 0) {
    message.warning('请先选择需要删除的项');
    return;
  }

  Modal.confirm({
    title: '确认删除',
    content: `你确定要删除选中的 ${selectedRows.length} 项吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      const ids = selectedRows.map(item => item.id);
      try {
        const { msg } = await deleteMultiple(ids); // ❗️这里是你定义的 API，传数组 ID
        const $table = GridApi.grid;
        message.success(msg || '删除成功');
        $table.commitProxy('query'); // ✅ 删除成功后刷新表格数据
      } catch (err) {
        message.error('删除失败，请稍后重试');
      }
    },
  });

  
};


const downtemlpate = async() => {
 const { data } = await getdownloadtemplate();
 console.log(data)
 window.location.href=data.url;
}



const openDialogCopy = async (row?: DataType) => {
  const id = row?.id || 0;
  router.push({
    name: `PortalParts${code.value}Detail`,
    params: { 
      code: code.value,
      id: id // 0表示新增
    },
    query: {
      copyFrom: row?.id // 明确表示从哪个ID复制
    }
  });
};






onMounted(async () => {

  const res = await getYears();
  yearOptions.value = Array.isArray(res?.data?.list)
    ? res.data.list.map((item) => ({
        label: `${item.year}`,
        value: item.id,
      }))
    : [];


  const param = queryStringToObject(route.meta.param as string);
  if (param?.code) {
    code.value = param.code;
  }
  const {
    data: { list },
  } = await getArticleSelectCategorys({ code: param.code });
  GridApi.formApi.updateSchema([
    {
      dependencies: {
        trigger: (values) => {
          if (values.category_id)
            GridApi.query({ category_id: values.category_id });
        },
        // 随意一个字段改变时，都会触发
        triggerFields: ['category_id'],
      },
      componentProps: {
        placeholder: $t('page.common.Please Select') + ` ${viewTitle}`+$t('page.common.Category'),
        treeData: list,
        fieldNames: {
          value: 'id',
          key: 'id',
          label: 'name',
          children: 'children',
        },
      },
      fieldName: 'category_id',
    },
  ]);







  const handleCustomImport = () => {
  // 举例：弹出上传窗口或打开上传组件
  Modal.info({
    title: '自定义上传',
    content: '这里实现你自己的上传逻辑，比如弹出上传框、选文件、调用接口等',
  });
};






});
</script>

<template>
  <Page auto-content-height>
    <Grid :table-title="`${viewTitle}`+$t('page.common.List')" :export-config="exportConfig"        @toolbar-button-click="handleToolbarClick" ref="gridRef">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="openDialog()">
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          {{$t('page.common.Add')}} {{ viewTitle }}
        </Button>
    

          <VbenButton @click="openDeleteConfirm()" class="mr-2">{{$t('page.common.Selected')}} {{$t('page.common.Delete')}}</VbenButton>
          
          <Modal v-model:visible="modalVisible" title="确认删除" class="w-[600px]">
            <template #default>
              <p>你确定要删除选中的 {{ selectedRows.length }} 项吗？此操作无法恢复。</p>
            </template>
            <template #footer>
              <VbenButton @click="modalVisible = false">取消</VbenButton>
              <VbenButton type="primary" danger @click="openDeleteConfirm()">确认删除</VbenButton>
            </template>
          </Modal>


        



       
        <!-- <VbenButton @click="downtemlpate()" class="mr-2">下载模版</VbenButton> -->
      </template>
      <template #status="{ row }">
        <Space warp>
          <Tooltip :title="row.post_status ? '已发布' : '草稿'">
            <Button
              shape="circle"
              type="dashed"
              @click="handleChangeStatus(row, 'publish')"
            >
              <template #icon>
                <span class="anticon">
                  <Icon v-if="row.post_status" icon="ri:check-fill" />
                  <Icon v-else icon="ri:close-fill" />
                </span>
              </template>
            </Button>
          </Tooltip>
          <Tooltip v-if='0' :title="row.is_top ? '已置顶' : '未置顶'">
            <Button
              shape="circle"
              type="dashed"
              @click="handleChangeStatus(row, 'top')"
            >
              <template #icon>
                <span class="anticon">
                  <Icon v-if="row.is_top" icon="ri:arrow-up-line" />
                  <Icon v-else icon="ri:arrow-down-line" />
                </span>
              </template>
            </Button>
          </Tooltip>
          <Tooltip v-if='0' :title="row.recommended ? '已推荐' : '未推荐'">
            <Button
              shape="circle"
              type="dashed"
              @click="handleChangeStatus(row, 'recommended')"
            >
              <template #icon>
                <span class="anticon">
                  <Icon v-if="row.recommended" icon="ri:fire-fill" />
                  <Icon v-else icon="ri:fire-line" />
                </span>
              </template>
            </Button>
          </Tooltip>
        </Space>
      </template>

      <template #post_title="{ row }">
            <a :href="`${baseUrl}parts/${row.slug}`" target="_blank">{{row.post_title}}</a>
      </template>

      <template #action="{ row }">
        <Space>
          <Button @click="openDialogCopy(row)">复制</Button>
          <Button type="primary" @click="openDialog(row)">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            编辑
          </Button>
          <Popconfirm
            cancel-text="否"
            ok-text="是"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <Button danger type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:delete-bin-line" />
                </span>
              </template>
              删除
            </Button>

          </Popconfirm>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
<style lang="scss">
     .vxe-grid--layout-header-wrapper{
      margin-bottom: -1rem;
     }
</style>